<?php

namespace app\admin\controller;

use app\model\BizGoodsOrderModel;
use app\model\BizGoodsModel;
use app\model\BizModel;
use app\model\UserModel;
use support\Request;
use support\Response;
use Exception;
use app\model\BizGoodsTicketModel;
use support\Db;
use app\model\Util;

class BizGoodsOrderController
{
    /**
     * 获取订单列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $goodsTitle = $request->get('goods_title', '');
            $phone = $request->get('phone', '');

            $query = BizGoodsOrderModel::whereNull('biz_goods_order.deleted_at')
                ->orderBy('biz_goods_order.id', 'desc');

            // 按商品名称搜索
            if (!empty($goodsTitle)) {
                $query->whereExists(function ($q) use ($goodsTitle) {
                    $q->select(Db::raw(1))
                        ->from('biz_goods')
                        ->whereRaw(table_with_prefix('biz_goods') . '.id = ' . table_with_prefix('biz_goods_order') . '.biz_goods_id')
                        ->where('biz_goods.title', 'like', '%' . $goodsTitle . '%');
                });
            }

            // 按手机号搜索
            if (!empty($phone)) {
                $query->whereExists(function ($q) use ($phone) {
                    $q->select(Db::raw(1))
                        ->from(table_with_prefix('user'))
                        ->whereRaw(table_with_prefix('user') . '.id = ' . table_with_prefix('biz_goods_order') . '.user_id')
                        ->where(table_with_prefix('user') . '.phone', 'like', '%' . $phone . '%');
                });
            }

            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['paid_at'] = $item->paid_at ? date('Y-m-d H:i:s', $item->paid_at) : '';

                // 格式化状态
                $item['status_text'] = $this->getStatusText($item->status);

                // 获取商品信息
                $bizGoods = BizGoodsModel::find($item->biz_goods_id);
                if ($bizGoods) {
                    $item['goods_title'] = $bizGoods->title;
                    $item['goods_image'] = $bizGoods->image;
                } else {
                    $item['goods_title'] = '商品已删除';
                    $item['goods_image'] = '';
                }

                // 获取用户信息
                $user = UserModel::find($item->user_id);
                if ($user) {
                    $item['user_phone'] = $user->phone;
                    $item['user_nickname'] = $user->nickname;
                } else {
                    $item['user_phone'] = '用户已删除';
                    $item['user_nickname'] = '用户已删除';
                }

                $biz = BizModel::find($item->biz_id);
                $item['biz_name'] = $biz ? $biz->name : '';
            }

            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取订单详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = $request->get('id');

            if (empty($id)) {
                throw new Exception('订单ID不能为空');
            }

            $order = BizGoodsOrderModel::where('id', $id)
                ->whereNull('deleted_at')
                ->first();

            if (!$order) {
                throw new Exception('订单不存在');
            }

            // 格式化时间
            $order['created_at'] = date('Y-m-d H:i:s', $order->created_at);
            $order['paid_at'] = $order->paid_at ? date('Y-m-d H:i:s', $order->paid_at) : '';
            $order['updated_at'] = date('Y-m-d H:i:s', $order->updated_at);

            // 格式化状态
            $order['status_text'] = $this->getStatusText($order->status);

            // 获取商品信息
            $bizGoods = BizGoodsModel::find($order->biz_goods_id);
            if ($bizGoods) {
                $order['goods_title'] = $bizGoods->title;
                $order['goods_image'] = Util::path($bizGoods->image);
                $order['goods_price'] = $bizGoods->price;
            } else {
                $order['goods_title'] = '商品已删除';
                $order['goods_image'] = '';
                $order['goods_price'] = 0;
            }

            // 获取用户信息
            $user = UserModel::find($order->user_id);
            if ($user) {
                $order['user_phone'] = $user->phone;
                $order['user_nickname'] = $user->nickname;
            } else {
                $order['user_phone'] = '用户已删除';
                $order['user_nickname'] = '用户已删除';
            }

            return json([
                'data' => $order,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取状态文本
     * @param string $status
     * @return string
     */
    private function getStatusText($status): string
    {
        $statusMap = [
            'unpay' => '未支付',
            'paid' => '已支付',
            'cancelled' => '已取消',
            'refunded' => '已退款'
        ];

        return $statusMap[$status] ?? '未知状态';
    }

    public function tickets(Request $request): Response
    {
        $id = $request->get('id');
        $tickets = BizGoodsTicketModel::where('order_id', $id)->get();
        foreach ($tickets as &$ticket) {
            $ticket['created_at'] = date('Y-m-d H:i:s', $ticket->created_at);
            $ticket['used_at'] = $ticket->used_at ? date('Y-m-d H:i:s', $ticket->used_at) : false;
        }
        return json([
            'data' => $tickets,
            'msg' => '获取成功',
            'code' => 20000
        ]);
    }
}
